package com.wad.utlis;

/**
 * @author wad
 * @date 2022/11/11 11:09
 * @project JWT_DEMO2
 **/

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具类，类中方法
 * getToken() static param:Map 创建token
 * verifyToken()
 */
public class JWTUtil {

    private static final String SIGNATURE="7&&34*00WADhSNN";//设置默认加密的密钥明文

    private static final Long JWT_DEFAULT_TTL=60*60*1000L;//设置默认jwt过期时间


    /**
     * 创建token令牌
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */

    public static String getToken(Map<String,String> map) throws UnsupportedEncodingException {
        JWTCreator.Builder builder = JWT.create();//创建JWT建造器
        map.forEach((k,v)->{//添加payload负载
            builder.withClaim(k,v);
        });
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DATE,7);
        return builder.withExpiresAt(calendar.getTime()).//指定过期时间
                sign(Algorithm.HMAC256(SIGNATURE));//用加密算法加密密钥，添加签名
    }


    /**
     * 验证token
     * @param token
     * @throws UnsupportedEncodingException
     */
    public static void verifyToken(String token) throws UnsupportedEncodingException {
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }


    /**
     * 得到token中的信息
     * @param token
     * @return
     * @throws UnsupportedEncodingException
     */
    public static DecodedJWT getTokenInfo(String token) throws UnsupportedEncodingException {
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
}
